package com.uinnova.springboot.web.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
*@author 王刚
*@date 2019-01-05 12:03
*preHandle执行过程 在拦截链中，preHandle为true则继续寻找下一个拦截器的preHandle，拦截器链执行完后从最后返回执行afterCompletion
* 回调链中，有一个preHandle为false，返回上一个拦截器的afterCompletletion方法，后面的拦preHandle不执行
*/
@Slf4j
public class MyInterceptor implements  HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*
        *@author 王刚
        *@date 2019-01-09 09:31
        *测试用户登陆，登陆以后就不拦截，未登陆的拦截到登陆页面
        */

        HttpSession  session = request.getSession();
        if(session.getAttribute("testInterceptor") != null){
            return true;
        }else{
            response.sendRedirect("/jail/interceptor/login");
            return false;
        }
//        log.info("myInterceptor-preHandler>>>在请求处理之前调用（controller方法执行之前）");
//        request.getRequestURI();
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("myInterceptor-postHandle>>>在请求处理之后，试图渲染之前调用（controller方法执行之后");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("myInterceptor-afterCompletion>>>在请求处理之后，在DispatcherServlet渲染视图之后调用(主要进行资源清理工作）");
    }
}
